package top.wenzz.manage.system.manage.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.wenzz.manage.system.manage.entity.SysUser;
import top.wenzz.manage.system.manage.feign.ConfigCenterFeign;
import top.wenzz.manage.system.manage.service.SysUserService;
import top.wenzz.commons.utils.ExceptionUtils;
import top.wenzz.commons.utils.SpringSecurityUtils;
import top.wenzz.commons.utils.StringUtils;
import top.wenzz.commons.vo.RetMsg;
import top.wenzz.commons.web.BasicController;

/**
 * 个人中心Controller
 * Created by cui-fate on 2017/7/16.
 */
@RestController
@RequestMapping("personal")
public class PersonalCenter extends BasicController {

    @Autowired
    private SysUserService userService;

    @RequestMapping( value = "updatePassword", method = RequestMethod.POST )
    public Object updatePassword(@RequestParam String oldPassword, @RequestParam String password,
                                 @RequestParam String confirmPassword) {
        SysUser user = userService.getOne(SpringSecurityUtils.getUserByContext().getId());
        oldPassword = StringUtils.passwordEncrypt(user.getUsername(), oldPassword, user.getSalt());
        if(!oldPassword.equals(user.getPassword()))
            return RetMsg.error("原密码不正确");
        if(!password.equals(confirmPassword))
            return RetMsg.error("新密码与确认密码输入不相同");
        String ret;
        try {
            user.setSalt(StringUtils.getRandom(6));
            user.setPassword(StringUtils.passwordEncrypt(user.getUsername(), password, user.getSalt()));
            ret = userService.update(user);
            userService.shotOff(user.getUsername());// 用户下线
        } catch (Exception e) {
            ret = ExceptionUtils.getExceptionMsg(e);
        }
        return ret(ret, "密码修改成功");
    }

    @RequestMapping( value = "getUserInfo", method = RequestMethod.POST )
    public Object getUserInfo() {
        SysUser user = userService.getOne(SpringSecurityUtils.getUserByContext().getId());
        return RetMsg.success(SysUser.builder()
                .username(user.getUsername())
                .name(user.getName())
                .sex(user.getSex())
                .staffId(user.getStaffId())
                .build()
        );
    }

    @RequestMapping( value = "updateUserInfo", method = RequestMethod.POST )
    public Object updateUserInfo(@RequestBody SysUser entity) {
        SysUser user = userService.getOne(SpringSecurityUtils.getUserByContext().getId());
        user.setName(entity.getName());
        user.setSex(entity.getSex());
        user.setStaffId(entity.getStaffId());
        String ret = null;
        try {
            userService.updateEntity(user);
        } catch (Exception e) {
            ret = ExceptionUtils.getExceptionMsg(e);
        }
        return ret(ret, "保存成功");
    }
}
